#include "index.h"
#include "ui_index.h"
#include <QUuid>
#include <QJsonObject>
#include <QJsonDocument>

Index::Index(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Index)
{
    ui->setupUi(this);
    socket=new QWebSocket();
    connect(socket, SIGNAL(connected()), this, SLOT(slotConnected()));
    //    connect(socket, SIGNAL(disconnected()), this, SLOT(slotDisconnected()));
    //connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotError(QAbstractSocket::SocketError)));
    connect(socket, SIGNAL(textMessageReceived(QString)), this, SLOT(slotRecvTextMsg(QString)));

}

Index::~Index()
{
    delete ui;
}

void Index::on_pushButton_listen_clicked()
{
    QUrl url("wss://ws-api.binance.com/ws-api/v3");
    socket->open(url);
    ui->textBrowser->append("start connect....\n");
}

void Index::on_pushButton_close_clicked()
{

    if(socket!=0){
        socket->deleteLater();
        socket=0;
        ui->textBrowser->setText("establish disconnect");
    }
}

void Index::slotConnected()
{
    // 准备要发送的JSON数据
    QJsonObject message;
    message["id"] = QUuid::createUuid().toString(); // 生成UUID
    message["method"] = "exchangeInfo";

    QJsonObject params;
    params["symbol"] = "BNBUSDT";
    message["params"] = params;

    // 将JSON对象转换为字符串
    QJsonDocument doc(message);
    QString jsonString = doc.toJson(QJsonDocument::Compact);
    socket->sendTextMessage(jsonString);
    ui->textBrowser->append("ex\n");
}

void Index::slotRecvTextMsg(QString message)
{

    ui->textBrowser->setText(message+"\n");

}
